package org.xxf.tdengine.demo.netty;

import com.hivemq.client.mqtt.MqttClient;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.lifecycle.MqttClientAutoReconnect;
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext;
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedListener;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class MqttManager {

    public static void main(String[] args) {
        String clientId = "test@"+NettyConstants.CLIENT_SUFFIX;
        String password = SecureUtils.AESDecryp(clientId);

        Mqtt5AsyncClient client = MqttClient.builder()
                .useMqttVersion5()
                .identifier(clientId)
                .serverHost(NettyConstants.URL)
                .serverPort(NettyConstants.PORT)
                .simpleAuth().username(clientId).password(password.getBytes()).applySimpleAuth()
                .automaticReconnect(MqttClientAutoReconnect.builder().initialDelay(1, TimeUnit.SECONDS).maxDelay(1, TimeUnit.SECONDS).build())
                .addDisconnectedListener(new MqttClientDisconnectedListener() {
                    @Override
                    public void onDisconnected(MqttClientDisconnectedContext context) {
                        System.out.println("Disconnected: "+context.getSource().toString());
                        System.out.println("Disconnected: "+context.getClientConfig().toString());
                        context.getCause().printStackTrace();
                    }
                })
                .buildAsync();
        System.out.println("over 1");
        client.connectWith().keepAlive(NettyConstants.KEEY_ALIVE).send().whenComplete(((mqtt5ConnAck, throwable) -> {
                    System.out.println("return connect ack");
            if (throwable != null) {
                System.out.println(throwable.getMessage());
                throwable.printStackTrace();
            }else{
                System.out.println("Connected: "+mqtt5ConnAck.getReasonCode());
                System.out.println("Connected: "+mqtt5ConnAck.getReasonString());
                System.out.println("start subscrible");
                client.subscribeWith().topicFilter("+/+/report/").qos(MqttQos.AT_MOST_ONCE).callback(mqtt5Publish -> {
                    ByteBuffer byteBuffer = mqtt5Publish.getPayload().orElse(null);
                    String str = byteBuffer == null ? "" : StandardCharsets.UTF_8.decode(byteBuffer).toString();
                    System.out.println("received msg["+ mqtt5Publish.getTopic() +"]: " + str);
                }).send().whenComplete((mqtt5SubAck, throwable1) -> {
                    System.out.println("return subscrible ack");
                    if (throwable1 != null) {
                        System.out.println(throwable.getMessage());
                        throwable.printStackTrace();
                    }else{
                        System.out.println("subscrible: "+mqtt5ConnAck.getReasonCode());
                        System.out.println("subscrible: "+mqtt5ConnAck.getReasonString());
                    }
                });
            }
        }));

//        TimerTask task = new TimerTask() {
//            public void run() {
//                client.publishWith().topic("test/aa")
//                        .payload(String.format("hello,%s", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).getBytes(Charset.forName("UTF-8")))
//                        .send().whenComplete((mqtt5PublishResult, throwable) -> {
//
//                            System.out.println("return publish ack");
//                            if (throwable != null) {
//                                System.out.println(throwable.getMessage());
//                                throwable.printStackTrace();
//                            }else{
//                                System.out.println("publish: "+mqtt5PublishResult.getError().orElse(null));
//                            }
//                });
//            }
//        };
//        Timer timer = new Timer();
//        timer.scheduleAtFixedRate(task, 0, 1000);

        System.out.println("over");

    }

}
